package com.seewo.dubbo.debugger.admin.common;

import com.alibaba.dubbo.common.URL;
import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * @author chenliangliang
 * @date 2018/7/29
 */
public class RedisRegistry extends AbstractServiceDiscovery<Jedis> {

    private volatile Jedis jedis;

    public RedisRegistry(String redisAddress, int connectionTimeout) {
        super(redisAddress, connectionTimeout);
    }

    public RedisRegistry(String redisAddress) {
        super(redisAddress);
    }

    @Override
    protected Jedis getClient() {
        if (jedis == null) {
            synchronized (RedisRegistry.class) {
                if (jedis == null || !jedis.isConnected()) {
                    String[] str = address.split(":");
                    jedis = new Jedis(str[0], Integer.parseInt(str[1]), connectionTimeout);
                }
            }
        }
        return jedis;
    }


    @Override
    public List<URL> getServiceProvider(String service) {
        if (StringUtils.isEmpty(service)) {
            return Collections.emptyList();
        }
        Jedis client = getClient();
        final String key = Constants.DUBBO_PREFIX + "/" + service + Constants.DUBBO_PROVIDERS;
        Set<String> hkeys = client.hkeys(key);
        List<URL> urls = new ArrayList<>();
        for (String urlStr : hkeys) {
            URL url = URL.valueOf(URL.decode(urlStr));
            urls.add(url);
        }
        return urls;
    }

    @Override
    public List<List<URL>> getEnableServiceProviders() {
        Jedis client = getClient();
        String pattern = Constants.DUBBO_PREFIX + "/*" +Constants.DUBBO_PROVIDERS;
        Set<String> keys = client.keys(pattern);
        List<List<URL>> res = new ArrayList<>();
        List<URL> urls;
        for (String key : keys) {
            urls = new ArrayList<>();
            Set<String> hkeys = jedis.hkeys(key);
            for (String hkey : hkeys) {
                URL url = URL.valueOf(URL.decode(hkey));
                urls.add(url);
            }
            res.add(urls);
        }
        return res;
    }

}
